#include <iostream>
#include <sstream>
#include <fstream>
#include <filesystem>  
#include "../include/controller.h"
#include "../include/car.h"
using namespace std;

Controller::Controller(){
    // 初始化学生列表
    vector<string> lines = readFile(PATH_STUDENT);
        for (const auto& line : lines) {  
            string studentName;  
            string studentId;
            std::istringstream iss(line);  
            std::string key, value;  
            char delimiter = ',';  
    
            // 解析姓名  
            if (std::getline(iss, key, ':') && key == "姓名") {  
                std::getline(iss, studentName, delimiter);  
    
                // 跳过"学号:"部分，直接读取学号（注意：这里假设学号后没有额外的逗号或空格）  
                iss.ignore(std::numeric_limits<std::streamsize>::max(), ':'); // 忽略到下一个':'  
                iss >> studentId;
                Student student(studentId, studentName);
            // iss >> student.id; // 读取学号（这里假设学号后没有额外的空格，但如果有，可以使用std::getline再次读取）  
    
                // 如果需要，可以添加额外的错误检查，比如确保iss的状态是好的  
                students.push_back(student);  
            }  
            // 注意：这里没有处理格式不正确的行，如果数据可能格式不正确，应该添加错误处理逻辑  
        }  
    namespace fs = std::filesystem; 
    // 初始化小车列表
    fs::path directoryPath = "../data/";  
  
    try {  
        // 检查路径是否存在且是一个目录  
        if (!fs::exists(directoryPath) || !fs::is_directory(directoryPath)) {  
            std::cerr << "目录不存在或不是一个目录: " << directoryPath << std::endl;  
            return;  
        }  
  
        // 遍历目录中的文件  
        for (const auto& entry : fs::directory_iterator(directoryPath)) {  
            // 获取文件名  
            std::string fileName = entry.path().filename().string();  
  
            // 判断文件名是否包含 "car"  
            if (fileName.find("car") != std::string::npos) {  
                string studentName, studentId, carId, chassisId;
                lines = readFile("../data/"+fileName);
                for (const auto& line : lines) {
                    size_t colonPos = line.find(':');
                    if (colonPos != std::string::npos) {
                        std::string key = line.substr(0, colonPos);
                        std::string value = line.substr(colonPos + 1); // 忽略冒号后的空格

                        // 去除首尾空格
                        value.erase(0, value.find_first_not_of(" \t\n\r\f\v")); // 前导空格
                        value.erase(value.find_last_not_of(" \t\n\r\f\v") + 1); // 尾随空格

                        // 匹配关键字
                        if (key == "姓名") {
                            studentName = value;
                        } else if (key == "学号") {
                            studentId = value;
                        } else if (key == "carId") {
                            carId = value;
                        } else if (key == " Chassis ID") {
                            chassisId = value;
                            break;
                        }
                    }
                }
                std::cout << "fileName:" << fileName << endl;
                std::cout << "name:" << studentName <<endl;
                std::cout << "studentId:" << studentId <<endl;
                std::cout << "carId:" << carId << endl;
                std::cout << "chassisId:" << chassisId << endl;
                SmartCar tempCar = (carId, chassisId);
                tempCar.setStudent(Student(studentId, studentName));
                cars.push_back(tempCar);
            }  
        }  
    } catch (const fs::filesystem_error& e) {  
        std::cerr << "文件系统错误: " << e.what() << std::endl;  
        return;  
    }  

};

vector<string> Controller::readFile(string fileName){
    std::ifstream file(fileName); // 替换"example.txt"为你的文件名  
    std::string line;  
    std::vector<std::string> lines;  
  
    if (file.is_open()) {  
        while (getline(file, line)) { // 使用getline()函数按行读取  
            if (!line.empty() && line.back() == '\n') {  
                line.pop_back();  
            } 
            lines.push_back(line); // 将读取的行添加到vector中  
        }  
        file.close();  
    } else {  
        std::cout << "Unable to open file";  
    }  
    return lines;
}



void Controller::recordCar(){

    while (true)
    {
        std::cout<<"请分别输入小车ID和底盘ID，输入‘q’退出录入：" << std::endl;
        std::string carId, chassisId;
        std::cin >> carId ;
        if(carId=="q"){return;}
        cin>> chassisId;
        if(carId.size()==16 && chassisId.size()==8){
            cars.push_back(SmartCar(carId, chassisId));
        }else{
            cout << "小车ID为cqusn打头的16位数字+字母，底盘ID为dp打头的8位数字+字母，请重新输入：" << endl;
        }
        

    }

}

void Controller::allocationCar(){
    
    while (true)
    {
        cout << "请输入小车Id和学生学号来分配小车，输入‘q’退出：" << endl;
        string carId, studentId;
        cin  >> carId;
        if(carId=="q"){return;}
        cin >> studentId;
        bool foundStudent=false, foundCar=false;
        Student tempStudent;
        SmartCar tempCar("asdgsh", "sagh");
        for (const auto& student : students) {  
            if(student.getId()==studentId){
                foundStudent = true;
                tempStudent = student;
            }
        } 
        for (const auto& car:cars){
            if(car.getCarId()==carId){
                foundCar=true;
                tempCar=car;
            }
        }
        if (foundCar==true && foundStudent==true){
            string filePath = "../data/car_"+tempCar.getCarId()+".txt";

            if(std::filesystem::exists(filePath)){
                cout << "该小车已经被分配！" << endl;
                continue;
            }
            tempCar.setStudent(tempStudent);
            std::ofstream file(filePath, std::ios::app);  

            if (  file.is_open()) {  

                // 写入学生信息
                tempCar.writeToFile(file);
                file.close();  
                cout << "分配成功！" << endl;
            } else {  
                cout << "打开文件失败！" << endl;
            }  
        }else{
            cout << "找不到该小车或学生！" <<endl;
        }
        /* code */
    }
    
   
}

void Controller::displayStudentInformation(){
    std::string command;
    int index = 0;
    while (true){

        students[index].print();
        cin >> command;
        if(command=="q"){return;}
        if(command=="n" && index < int(students.size())-1){
            ++index;
        }
        if(command=="p" && index > 0){
            --index;
        }
        
    }
}

void Controller::displayCarInformation(){
        std::string command;
    int index = 0;
    while (true){

        cars[index].print();
        cin >> command;
        if(command=="q"){return;}
        if(command=="n" && index < int(cars.size())-1){
            ++index;
        }
        if(command=="p" && index > 0){
            --index;
        }
        
    }
}